﻿using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;

class Program
{
	//题目来源网址
	static private string BaseUrl = "https://www.ybjk.com/tiku/kms-1511.htm";
	private const int WaitTimeSeconds = 10;
	//下面路径填写题目保存的文件夹路径
	private const string FolderPath = @"E:\VSprogram\repos\DriverExam\DriverExam\Resources\Subject4";
	static private FileStream fileStream;
	static private StreamWriter streamWriter;
	static private int EndPage=2;//爬取的页数
	static private string directoryPath;
	static void Main(string[] args)
	{
		ChromeOptions options = new ChromeOptions();
		options.AcceptInsecureCertificates = true;
		options.PageLoadStrategy = PageLoadStrategy.Eager;
		for (int i = 1; i <= EndPage; ++i,BaseUrl = GetNewURL(BaseUrl, i))
		{
			Console.WriteLine($"正在爬取{BaseUrl}");
			using (IWebDriver driver = new ChromeDriver(options))
			{
				try
				{
					WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(WaitTimeSeconds));
					driver.Navigate().GoToUrl(BaseUrl);
					IReadOnlyCollection<IWebElement> details = wait.Until(p => p.FindElements(By.CssSelector("li.fcc table tbody tr td a")));
					foreach (IWebElement detail in details)
					{
						ProcessQuestion(driver, wait, detail);
					}
				}
				catch (Exception ex)
				{
					Console.WriteLine(ex.Message);
				}
				Thread.Sleep(5000);
			}
			
		}
		Console.ReadKey();
	}

	static void ProcessQuestion(IWebDriver driver, WebDriverWait wait, IWebElement questionLink)
	{
		
		try
		{
			questionLink.Click();
			string originWindow = driver.CurrentWindowHandle;
			string newWindow = GetNewWindowHandle(driver, originWindow);
			driver.SwitchTo().Window(newWindow);

			IWebElement title = wait.Until(p => p.FindElement(By.CssSelector("div#WinContent div strong a")));
			if (!AddQuestionFile(int.Parse(title.Text.Split('.')[0].Trim()))) 
			{
				driver.Close();
				driver.SwitchTo().Window(originWindow);
				return;
			}
			streamWriter.WriteLine($"[{title.Text.Split('.')[1].Trim()}]");

			IReadOnlyCollection<IWebElement> options = wait.Until(p => p.FindElements(By.CssSelector("div#WinContent div ul li")));
			ProcessOptions(options);

			IWebElement analysis = wait.Until(p => p.FindElement(By.XPath("//*[@id=\"NoteContent\"]/p")));
			streamWriter.WriteLine($"[{analysis.Text}]");

			ProcessPicture(driver);
			driver.Close();
			driver.SwitchTo().Window(originWindow);
			streamWriter.Close();
			fileStream.Close();
		}
		catch (Exception ex)
		{
			Console.WriteLine(ex.Message);
		}
	}

	static string GetNewWindowHandle(IWebDriver driver, string originWindow)
	{
		foreach (string handle in driver.WindowHandles)
		{
			if (handle != originWindow)
			{
				return handle;
			}
		}
		throw new NoSuchWindowException("新窗口未找到");
	}

	static void ProcessOptions(IReadOnlyCollection<IWebElement> options)
	{
		foreach (IWebElement option in options)
		{
			try
			{
				IWebElement correctOption = option.FindElement(By.TagName("b"));
				streamWriter.WriteLine($"[F-{correctOption.Text}]");
			}
			catch (NoSuchElementException)
			{
				if (!(options.Count > 4 && option.Text.Contains("答案")))
				{
					streamWriter.WriteLine($"[{option.Text}]");
				}
				continue;
			}
		}
	}

	static void ProcessPicture(IWebDriver driver)
	{
		try
		{
			Thread.Sleep(2000);
			IWebElement picture = driver.FindElement(By.XPath("//*[@id=\"WinContent\"]/div[1]/div/img"));
			string url=picture.GetAttribute("src");
			WebClient webClient = new WebClient();
			Uri URL = new Uri(url);
			webClient.DownloadFile(URL,Path.Combine(directoryPath,@"picture.webp"));
		}
		catch (NoSuchElementException)
		{
			return;
		}
	}
	static bool AddQuestionFile(int id)
	{
		directoryPath = Path.Combine(FolderPath, $"{id}");
		
		if (!Directory.Exists(directoryPath))
		{
			Directory.CreateDirectory(directoryPath);
			string fileName = Path.Combine(directoryPath, @"Question.txt");
			fileStream = new FileStream(fileName, FileMode.Append, FileAccess.Write);
			streamWriter = new StreamWriter(fileStream, Encoding.UTF8);
			streamWriter.AutoFlush = true;
			return true;
		}
		else
		{
			return false;
		}
	}
	static string GetNewURL(string url,int pageid)
	{
		string newUrl=url.Split('_')[0].TrimEnd('.','h','t','m')+ $"_{pageid}.htm";
		return newUrl;
	}
	
}